<template>
  <div class="header">
    <div>
      <el-icon>
        <Refresh/>
      </el-icon>
    </div>

    <div>阿达西司机端</div>
    <div>
      <el-icon>
        <Bell/>
      </el-icon>
    </div>
  </div>
  <div class="list">
    <div v-for="item in tableData"   class="list-item">
      <div class="icon" >
        <el-icon> <StarFilled/> </el-icon>
      </div>
      <div class="content" >
        <div class="route">{{departure[item.id]}} <img alt="" class="img" src="../assets/r1.png"> {{destination[item.id]}}</div>
        <div class="startTime" > 出发时间:{{item.startDate+item.startTime}} </div>
        <div class="passengerTripNumPassengers"> 已拼<span style="color: red;">{{item.passengerTripNumPassengers}}</span>人 </div>
      </div>
    </div>
  </div>

</template>
<script lang="ts" setup>
import { ref , onMounted , onUnmounted} from 'vue';
import service from "@/utils/request";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";

const router = useRouter();
const tableData=ref([])
const route =ref([])
const departure=ref([])
const destination=ref([])

/**
 * 判断状态是不是代接受
 */



const fetchData =  () => {
  try {
    tableData.value = [];
    service.get('/vehicle-trip/vehiclePassenger/query')
        .then(res=>{
          console.log(res.data.data)
          for (let i = 0 ;i < res.data.data.length;i++){
            if(res.data.data[i].status=="待接受"){
              tableData.value.push(res.data.data[i])

              const date = new Date(res.data.data[i].date);
              // 使用合适的格式来显示日期和时间
              const options = { year: 'numeric', month: '2-digit', day: '2-digit' } as Intl.DateTimeFormatOptions;
              const formattedDate = date.toLocaleDateString(undefined, options);

              let datetime = new Date(res.data.data[i].startTime);
              let offset = -8 * 60 * 60 * 1000; // PT is 8 hours behind UTC
              datetime.setTime(datetime.getTime() + offset);
              /*let dateString = datetime;
// 创建一个新的Date对象
              let datetime2 = new Date(dateString);
// 获取年、月、日、时、分
              let hour = datetime2.getHours()+8;
              let minute = datetime2.getMinutes();
// 格式化日期时间
              let formattedDateTime = ` ${hour}:${minute < 10 ? '0' + minute : minute}`;
              res.data.data.data[i].startTime=formattedDateTime;*/
            }
          }
        })
  } catch (error) {
    console.log('获取数据时出现问题:', error);
  }
};

/**
 * 长轮询检查数据库更新
 */
const longPolling = async () => {
  try {
    const response = await service.get('/vehicle-trip/vehiclePassenger/query');
    const newData = response; // 接收到的新数据

    if (JSON.stringify(newData.data.data) !== JSON.stringify(tableData.value)) {
      // 仅当数据库发生变化时更新 tableData
      tableData.value = newData.data.data.filter(item => item.status === "待接受");
      updateDepartureAndDestination();
    }
    // 延迟一段时间再进行下一次长轮询请求
    setTimeout(longPolling, 10000); // 根据实际需求调整延迟时间

  } catch (error) {
    // 处理错误
    console.log('长轮询出现问题:', error);

    // 延迟一段时间再进行下一次长轮询请求（即使出现错误）
    setTimeout(longPolling, 10000); // 根据实际需求调整延迟时间

  }
  fetchData();
};
async function updateDepartureAndDestination() {
  departure.value = []; // 清空数组
  destination.value = []; // 清空数组
  for (let i = 0; i < tableData.value.length; i++) {
    const item = tableData.value[i];
    // 这里我们假设每个item都有一个route属性，这个属性是一个字符串，包含出发地和目的地，中间用"-"隔开。
    const parts = item.route.split("-");
    departure.value[item.id] = parts[0];
    destination.value[item.id] = parts[1];
  }
}
fetchData();
onMounted(() => {
  longPolling();
});
onUnmounted(() => {
});

</script>
<style lang='less' scoped>
.header {
  position: fixed;
  z-index: 1;
  display: flex;
  justify-content: space-between;
  background-color: #BDDCFF;
  height: 60px;
  width: 100%;
  line-height: 60px;
  color: #495e77;
  padding: 0 12px;
}

.list {
  margin-top: 70px;
  margin-left: 10px;
  margin-right: 10px;

  .list-item {
    display: flex;
    border: 1px solid #ccc;
    /* 主要边框 */
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2), 0 0 10px rgba(0, 0, 0, 0.15);
    /* 多重阴影 */
    padding: 10px;
    /* 内边距 */
    background-color: white;
    /* 背景颜色 */

    .icon {
      color: #75aeee;
      margin: 0px 10px;
    }

    .content {
      padding: 0px 10px;

      .startTime {
        font-size: 15px;
        font-weight: 500;
        margin-top: 10px;
        margin-bottom: 20px;
      }

      .passengerTripNumPassengers {
        font-size: 15px;
        font-weight: 500;
        margin-top: 10px;
        margin-bottom: 20px;


        .red {
          color: red;
        }
      }

      .img {
        width: 40px;
        height: 40px;
        vertical-align: middle;
      }
    }
  }

}</style>
